/*
 * Copyright (c) 2004-2005, Volatile-Engine All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the Volatile-Engine nor the
 * names of its contributors may be used to endorse or promote products derived
 * from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 */
package com.volatileengine.material.shader;

import java.lang.reflect.Field;
import java.util.List;

import com.volatileengine.material.shader.variable.PrimitiveShaderVariable;
import com.volatileengine.material.shader.variable.ShaderVariable;
import com.volatileengine.material.shader.variable.Uniform;
import com.volatileengine.platform.CreateShaderProgramReadCommand;
import com.volatileengine.platform.GPUChannel;
import com.volatileengine.platform.PlatformManager;
import com.volatileengine.platform.ReadAttributesReadCommand;
import com.volatileengine.platform.ReadUniformsReadCommand;
import com.volatileengine.resources.references.Handle;
import com.volatileengine.resources.references.Resource;

/**
 * TODO: Document me
 */
public class ShaderProgram implements Resource {

	private Handle<?> handle;
	private List<ShaderObject> objects;

	private List<ShaderVariable<?>> uniforms;
	private List<ShaderVariable<?>> attributes;

	public ShaderProgram(List<ShaderObject> objects) {
		this.objects = objects;

		GPUChannel channel = new GPUChannel();
		PlatformManager.instance().openChannel(channel);
		CreateShaderProgramReadCommand command = new CreateShaderProgramReadCommand(this);
		channel.put(command);

		// get the list of uniforms after the handle has been given
		ReadUniformsReadCommand readUniforms = new ReadUniformsReadCommand(this);
		channel.put(readUniforms);

		ReadAttributesReadCommand readAttribs = new ReadAttributesReadCommand(this);
		channel.put(readAttribs);

		channel.sync();

		uniforms = readUniforms.getObject();
		attributes = readAttribs.getObject();

		PlatformManager.instance().closeChannel(channel);

	}

	@SuppressWarnings("unchecked")
	public void register(Object obj) {
		long nano = System.nanoTime();
		Class<?> clazz = obj.getClass();

		// get all fields
		for (Field field : clazz.getDeclaredFields()) {
			// if this has a uniform
			if (field.isAnnotationPresent(Uniform.class)) {
				// register here
				String name = field.getName();

				// loop through the uniforms
				for (int i = 0; i < uniforms.size(); i++) {
					ShaderVariable temp = uniforms.get(i);

					// see if we have a uniform with that name and type

					if (name.equals(temp.getName())) {
						if (field.getType().isAssignableFrom(temp.getValue().getClass())) {
							field.setAccessible(true);

							// number primitive
							if (Number.class.isAssignableFrom(field.getType())) {
								PrimitiveShaderVariable<?> primVar = (PrimitiveShaderVariable<?>) temp;
								primVar.setReflectField(field);
								primVar.setReflectInstance(obj);
							}
							try {
								temp.setValue(field.get(obj));
							} catch (IllegalArgumentException e) {
								e.printStackTrace();
							} catch (IllegalAccessException e) {
								e.printStackTrace();
							}
						}
					}
				}

			}
		}
		System.out.println(System.nanoTime() - nano);

	}

	public List<ShaderVariable<?>> getShaderUniforms() {
		return uniforms;
	}

	public List<ShaderVariable<?>> getShaderAttributes() {
		return attributes;
	}

	public List<ShaderObject> getShaderObjects() {
		return objects;
	}

	public Handle<?> getHandle() {
		return handle;
	}
}
